/**
 * 2016年10月30日
 */
package io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
class Server{
	ServerSocket s;
	Socket client;
	public Server() throws IOException {
		// TODO Auto-generated constructor stub
		if(s==null){
			s = new ServerSocket(6666);
		}
		client = s.accept();
		File f = new File("C://temp.bin");
		byte []buffer = new byte[1024*1024];
		InputStream in = client.getInputStream();
		OutputStream out = new FileOutputStream(f);
		int length=0;
		while((length=(in.read(buffer)))!=-1){
			out.write(buffer,0,length);
			out.flush();
		}
		in.close();
		out.close();
		client.close();
	}
}
class Client{
	Socket s ;
	public Client() throws UnknownHostException, IOException {
		s = new Socket();
		s.connect(new InetSocketAddress("localhost",6666));
	}
	public void sendFile(File file) throws IOException{
		InputStream in = new FileInputStream(file);
		OutputStream out =  s.getOutputStream();
		byte []buffer = new byte[1024*1024];//1Mb
		int length = 0;
		while(((length=in.read(buffer))!=-1)){
			out.write(buffer,0,length);
		}
		in.close();
		out.close();
		s.close();
	}
}
public class TcpTransFile {
	public static void main(String args[]) throws IOException{
		Runnable r = ()->{
			try {
				Server s = new Server();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		};
		new Thread(r).start();
		Client c = new Client();
		c.sendFile(new File("D:\\userData.rar"));
	}
}
